<?php
/* 
 公共函数
*/

use Illuminate\Support\Facades\Storage;

date_default_timezone_set("PRC");
//当函数不存在的时候才去创建  function_exists:判断函数是否定义
if (!function_exists('randstr')) {
    /**
     * 获得随机字符串
     * @param string $len             需要的长度
     * @param boolean $special        是否需要特殊符号
     * @return string       返回随机字符串
     */
    function randstr($len = 8, $special = false)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if ($special) {
            // array_merge — 合并一个或多个数组
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;  //count: 数组中的单元数目
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位  mt_rand:返回随机整数
        }
        return $str;
    }
}

if (!function_exists('success')) {
    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param mixed  $msg    提示信息
     * @param mixed  $data   返回的数据
     * @return void
     * @throws HttpResponseException
     */
    function success($msg = '', $data = '')
    {
        $result = [
            'code' => 1,
            'msg'  => $msg,
            'data' => $data,
        ];

        return json_encode($result);
    }
}

if (!function_exists('error')) {
    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param mixed  $msg    提示信息
     * @param mixed  $data   返回的数据
     * @return void
     * @throws HttpResponseException
     */
    function error($msg = '', $data = '')
    {
        $result = [
            'code' => 0,
            'msg'  => $msg,
            'data' => $data,
        ];

        return json_encode($result);
    }
}
if (!function_exists('updload')) {
    /**
     * 保存上传一张图片
     * @param $file 上传图片
     * @return OBject $result 返回值
     * 'msg' 信息
     * 'data'  数据
     * 'code'  返回码       
     */

    function updload($file)
    {
        $result = [
            'msg' => '未上传图片',
            'data' => null,
            'code' => 0
        ];
        if (!$file) {
            return $result;
        }
        // 获取文件名字
        $ext = $file->extension();
        $randstr = randstr(10);
        $date = date("YmdHis", time());
        $time = date("Ymd", time());
        $name = $date . $randstr . '.' . $ext;
        // 获取到临时文件
        $paths = $file->getRealPath();
        $path = Storage::disk("uploads")->put($time . '/' . $name, file_get_contents($paths));
        if ($path) {
            $result['msg'] = '上传成功';
            $result['data'] = "/uploads/$time/$name";
            return $result;
        }
        $result['msg'] = $file->getErrorMessage();
        return $result;
    }
}
if (!function_exists('delete_picture')) {
    /**
     * 删除图片
     * @param $path 图片路径
     * @return bool
     */
    function delete_picture($path)
    {
        $path = str_replace('/uploads', '', $path);
        return Storage::disk('uploads')->delete($path);
    }
}
if (!function_exists('httpRequest')) {
    /**
     * 发起网络请求函数
     * @param $url 请求的URL
     * @param bool $params 请求的参数内容
     * @param int $ispost 是否POST请求
     * @param Arrary $headers 设置的请求头信息
     * @return bool|string 返回内容
     */
    function httpRequest($url, $params = false, $ispost = 0, $headers = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_FAILONERROR, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_HEADER, false);
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
}
if (!function_exists('build_code')) {
    /**
     * 生成唯一订单号
     * @param String $prefix 指定的订单前缀
     * @return String  返回字符串
     */

    function build_code($prefix = "")
    {
        @date_default_timezone_set("PRC");
        $order_id_main = date('YmdHis') . rand(10000, 99999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $osn = $prefix . $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT); //生成唯一订单号
        return $osn;
    }
}
if (!function_exists('updloads')) {
    /**
     * 保存上传的多张图片
     * @param $file 上传图片
     * @return OBject $result 返回值
     * 'msg' 信息
     * 'data'  数据
     * 'code'  返回码       
     */

    function updloads($files)
    {
        $result = [
            'msg' => '未上传图片',
            'data' => null,
            'code' => 0
        ];
        if (!$files) {
            return $result;
        }
        $list = [];
        foreach ($files as $file) {
            // 获取文件名字
            $ext = $file->extension();
            $randstr = randstr(10);
            $date = date("YmdHis", time());
            $time = date("Ymd", time());
            $name = $date . $randstr . '.' . $ext;
            // 获取到临时文件
            $paths = $file->getRealPath();
            $path = Storage::disk("uploads")->put($time . '/' . $name, file_get_contents($paths));
            if (!$path) {
                $result['msg'] = $file->getErrorMessage();
                return $result;
            }
            $list[] = "/uploads/$time/$name";
        }
        $result['code'] = 1;
        $result['msg'] = '上传成功';
        $result['data'] = implode(',', $list);
        return $result;
    }
}

if (!function_exists('query_express')) {
    /**
     * $no 快递单号
     * $type 快递公司
     */
    function query_express($no, $type = null)
    {
        // 自定义返回数据
        $success = [
            'result' => false,
            'msg' => '',
            'data' => null
        ];
        // 判断单号不能为空
        if (empty($no)) {
            $success['msg'] = "快递单号不能为空";
            return $success;
        }
        $data = [
            'no' => $no
        ];

        if (!empty($type)) {
            $data['type'] = $type;
        }

        // header 头信息验证  服务密钥
        $appcode = "655511a2d041401d97137f5ec11d9caf"; //开通服务后 买家中心-查看AppCode

        $headers = [
            'Authorization:APPCODE ' . $appcode
        ];
        $url = "http://wuliu.market.alicloudapi.com/kdi";
        $params = http_build_query($data);
        $result = httpRequest($url, $params, 0, $headers);
        //将json 转换为 php 数组
        $output = json_decode($result, true);
        if (empty($output) || $output['status'] != 0) {
            $success['result'] = false;
            $success['msg'] = $output['msg'] ?? '未查询到物流信息';
            return $success;
        } else {
            $success['result'] = true;
            $success['msg'] = '查询物流信息成功';

            $success['data'] = $output['result']['list'];
        }
        return $success;
    }
}
